package com.lyons.generate.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson2.JSON;
import com.lyons.generate.pojo.CodeGenerate;
import com.lyons.generate.pojo.CodeGenerateConfig;
import com.lyons.generate.service.CodeGenerateConfigService;
import com.lyons.generate.service.CodeGenerateService;

@Controller
public class CodeGenerateController {

	@Autowired
	private CodeGenerateService codeGenerateService;

	@Autowired
	private CodeGenerateConfigService configService;

	@GetMapping(value = { "/", "/index.html" })
	public String codeGenerate(Map<String, Object> map) {

		// 查询所有表信息
		List<CodeGenerate> list = codeGenerateService.queryAll();
		map.put("list", list);

		return "index";
	}

	@GetMapping("/init.html")
	public String init(Map<String, Object> map) {

		List<CodeGenerate> list = codeGenerateService.queryTableList();
		map.put("list", list);

		return "table";
	}

	@PostMapping("/save.html")
	public String save(CodeGenerate generate) {

		codeGenerateService.insertOrUpdate(generate);
		return "redirect:/";
	}

	@GetMapping("/configView.html")
	public String configView() {

		return "config";
	}

	@GetMapping(value = "/config.html")
	@ResponseBody
	public Object config(String table) {

		// 通过表名查询表字段信息
		List<CodeGenerateConfig> list = codeGenerateService.config(table.trim());

		Map<String, Object> map = new HashMap<>();
		map.put("code", 200);
		map.put("data", list);

		return map;
	}

	@PostMapping("/saveConfig.html")
	public String saveConfig(@RequestBody String json) {

		List<CodeGenerateConfig> list = JSON.parseArray(json, CodeGenerateConfig.class);
		configService.saveConfig(list);
		return "redirect:/";
	}

}
